package com.lct.todo.servlet;

import com.google.gson.Gson;
import com.lct.todo.bean.TaskBean;
import com.lct.todo.daoimpl.TaskDaoImpl;
import com.lct.todo.response.TaskAddResponse;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddTaskServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //基本设置
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter printWriter = response.getWriter();
        //插入
        TaskAddResponse addResponse;
        String taskName = request.getParameter("taskName");
        String taskCreateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TaskBean taskBean = new TaskBean(taskName, taskCreateTime, 0);
        int result = new TaskDaoImpl().insert(taskBean);
        if (result == 1) {
            addResponse = new TaskAddResponse(true, "", taskName, taskCreateTime);
        } else {
            addResponse = new TaskAddResponse(false, "系统异常", taskName, taskCreateTime);
        }
        printWriter.println(new Gson().toJson(addResponse));
        printWriter.flush();
        printWriter.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }
}
